var params = app.getRequestParams();
var txt = params.type == 1?'入':'出';
var xcode = params.type == 1?'OI':'OC';
$(function(){
    
    app.request({
        url:'store/select',
        success:function (resp) {
            initPage(resp.data);
        }
    });
    
});
var backEditFlag = true;
function initPage(storeData){
    
    
    $('#add span').html('新增'+txt+'库单');
    if(params.view==1){
        $('#create').hide();
    }
    
    $('#fixtable').fixgrid({
        noscroll:true,
        width:1000,
        columns:[
            [
                {field:'serialnumber',title:'',width:30},
                {field:'o',title:'操作',width:60,formatter:function () {
                        return gridOpt('#fixtable');
                    }},
                {
                    field:'productId',
                    title:'<span class="red">*</span>商品 -- 扫描枪录入<span init="off" style="position: relative;cursor: pointer;" smqlr="u"></span>',
                    width:200,
                    editor:'search',
                    searchData:function(that){
                        return $(that).parent().data().product;
                    },
                    click:datagridSearchClick,
                    url:'../../common/product_list.html',
                    editBefore:productEditBefore
                }
            ],
            [
                {field:'unitId',title:'<span class="red">*</span>'+txt+'库单位',width:120,editor:'combobox',editBefore:editBefore,
                    getData:function(cell,callback){
                        var rowData = cell.parent().data().product;
                        app.request({
                            url:'product/getMultiUnit',
                            data:{productId:rowData.id},
                            success:function (resp) {
                                var comboData = [{id:rowData.unitId,name:rowData.unitName}];
                                comboData.merge(resp.data);
                                callback(comboData);
                            }
                        });
                    },comboboxData:function (that) {
                        return $(that).data();
                    }
                },
                {field:'number',title:'<span class="red">*</span>'+txt+'库数量',width:120,editor:'decimal',editBefore:editBefore},
                {field:'storeId',title:'<span class="red">*</span>'+txt+'库仓库',width:120,editor:'combobox',editBefore:editBefore,
                    getData:function(cell,callback){
                        return callback(storeData);
                    },comboboxData:function (that) {
                        return $(that).data();
                    }
                },
                {field:'price',title:'<span class="red">*</span>'+txt+'库单价',width:120,editor:'decimal',editBefore:editBefore}
            ]
        ]
    });
    setBarCode();
    if(params.status==2){
        editable = false;
    }
    
    $('textarea[name="stoneOther.remarks"]').width($('#fixtable').width()-14);
    initButtons({service:'stoneOther',htmlName:'otherin?type='+params.type,orderText:'其它'+txt+'库',codePrefix:xcode,orderType:0,gridId:'#fixtable'});
    
    laydate.render({
        elem: '#order_date',value:new Date()
    });
    // 必须放在最后  所有代码要写在之前
    if(params.id){
        app.request({
            url:'stoneOther/getOrder',
            data:{id:params.id,otherType:params.type},
            success:function (resp) {
                initEdit(resp.data);
                layer.closeAll('loading');
            }
        });
    }else{
        $('#order_title').html('新增其他'+txt+'库单');
        for(var i=0 ; i < 5 ; i++){createRow();}
        layer.closeAll('loading');
    }
    $('#do_reset').html('新增其他'+txt+'库单');
    
}

function setBarCode(gridId){
    gridId = gridId ? gridId : '#fixtable';
    
    $(gridId+' span[smqlr="u"]').html('<i class="fa fa-toggle-on fa-rotate-180" style="color:gray;font-size:19px;position: absolute;"></i>');
    $(gridId+' span[smqlr="u"]').click(function () {
        var init = $(this).attr('init');
        if( init == 'off' ){
            $(this).attr('init','on');
            $(gridId+' span[smqlr="u"]').html('<i class="fa fa-toggle-on" style="color:#1D9D74;font-size:19px;position: absolute;"></i>');
        }else{
            $(this).attr('init','off');
            $(gridId+' span[smqlr="u"]').html('<i class="fa fa-toggle-on fa-rotate-180" style="color:gray;font-size:19px;position: absolute;"></i>');
        }
    });
}

//编辑初始化
function initEdit(data){

    var details = data.details;
    var order = data.stoneOther;
    
    init_edit_buttons(order);

    $('#order_title').html('编辑其他'+txt+'库单【'+order.code+'】');
    $('#order_date').val(app.time2str(parseInt(order.date)));
    $('textarea[name="stoneOther.remarks"]').val(order.remarks);

    for (var i=0 ; i<details.length ; i++){
        var detail = details[i];
        var product = {};
        product.id = detail.productId;
        product.name = detail.productName;
        createRow();
        var leftRow = $('#fixtable .ctx-left .vui-table .vui-table-row').eq(i);
        var rightRow = $('#fixtable .ctx-right .vui-table .vui-table-row').eq(i);
        var searchCell = leftRow.find('.vui-table-cell[field="productId"]');
        searchCell.data({product:product});
        searchCell.html(product.name);
        leftRow.data({product:product});
        rightRow.data({product:product});
        
        rightRow.find('.vui-table-cell[field="unitId"]').html(detail.unitName).data({value:detail.unitId,text:detail.unitName});
        rightRow.find('.vui-table-cell[field="number"]').html(app.div(detail.number,100).replace('.00',''));
        rightRow.find('.vui-table-cell[field="storeId"]').html(detail.unitName).data({value:detail.unitId,text:detail.unitName});
        rightRow.find('.vui-table-cell[field="price"]').html(app.div(detail.price,100));
        
    }
}


//保存
var accounts = [];
function saveAction(saveType,obj){
    var data = app.serializeForm();
    data['stoneOther.date'] =new Date(data['stoneOther.date']).getTime();
    data.saveType = saveType;
    $.each(details,function(i,row){
        for ( var n in row ){
            data["details["+i+"]."+n] = row[n];
            data["details["+i+"].ord"] = i;
        }
    });

    var url = 'stoneOther/insert';
    if(params.id){
        data['stoneOther.id'] = params.id;
        url = 'stoneOther/update';
    }
    data['stoneOther.otherType'] = params.type;
    doSave(url,data,saveType,obj);
}

//表单检查
var details = [],checkRowsTip = false;
function checkForm(){
    checkRowsTip = false;
    var txt = params.type == 1?'入':'出';
    var checkOptions = [
        {type:'input',name:'stoneOther.date',verify:[{type:'required'}]},
    ];

    if(app.checkForm(checkOptions)){
        checkRows();
        if(checkRowsTip)return false;
        if(details.length == 0){
            app.msg(layer,'至少填写一条商品记录',2);
            return false;
        }else{
            return true;
        }
    }

    return false;
}

function checkRows() {
    details = [];
    $('#fixtable .ctx-left .vui-table-row').each(function () {
        var product = getRowEleProduct($(this));
        if( product && product.id ){
            var n = $(this).attr('i');
            //body区域对应行
            var bodyTr = $('#fixtable .ctx-right .vui-table-row').eq(n);

            var detail = {productId:product.id};
            //仓库
            var store = getField(bodyTr,'storeId').data();
            if( !store.value ){
                app.msg(layer,'商品【'+product.name+'】未选择'+txt+'库仓库',2);
                checkRowsTip = true;
                return false;
            }
            detail.storeId = store.value;detail.companyId = -1;
            
            // 单位
            var unitNameData = getField(bodyTr,'unitId').data();
            detail.unitId = unitNameData.value;
            detail.unitMain = unitNameData.main ? 1 : 0;
            // 单价
            var priceStr = getField(bodyTr,'price').html();
            if( priceStr==null || priceStr.length == 0 ){
                app.msg(layer,'商品【'+product.name+'】未填写'+txt+'库单价',2);
                checkRowsTip = true;
                return false;
            }
            detail.price = app.mul(priceStr,app.DIV,0);
            // 数量
            detail.number = app.mul(getField(bodyTr,'number').html(),app.DIV,0);
            details.push(detail);
        }
    });
}

//商品选择后
function productSelected(cell){
    var obj = productSelectedCommon(cell);
    var product = obj.product;
    var rightRow = obj.rightRow;

    rightRow.find('.vui-table-cell[field="unitId"]').html(product.unitName).data({value:product.unitId,text:product.unitName});
    rightRow.find('.vui-table-cell[field="number"]').html(1);

}